package com.mes.task.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bstek.dorado.data.provider.Page;
import com.mes.common.dao.BasicDao;
import com.mes.task.dao.iface.IOperationTaskDao;
import com.mes.task.dao.iface.IPartTaskDao;
import com.mes.task.dao.iface.ITaskDao;
import com.mes.task.dao.iface.ITaskPartDao;
import com.mes.task.domain.OperationTask;
import com.mes.task.domain.PartTask;
import com.mes.task.domain.Task;
import com.mes.task.domain.TaskPart;

@Repository
public class TaskPartDao extends BasicDao<TaskPart> implements ITaskPartDao {
	
	@Autowired
	private ITaskDao taskDao;
	
	@Autowired
	private IOperationTaskDao operationTaskDao;
	
	@Autowired
	private IPartTaskDao partTaskDao;
	
	/**
	 * @author lcs
	 * @see 用于AO任务管理中齐套情况通过任务号获取齐套信息
	 * @param taskUid
	 * @param page
	 * @return
	 */
	@Override
	public List<TaskPart> getTaskPartByTaskUid(String taskUid, Page page) {
		  
		List<TaskPart> list = null;
		DetachedCriteria crit = DetachedCriteria.forClass(TaskPart.class);
		crit.createAlias("task", "t");
		crit.add(Restrictions.eq("taskUid", taskUid));
		if (page != null) {
			this.pagingQuery(page, crit);
		} else {
			list = this.query(crit, null);
		}
		return list;
	}

	
	@Override
	public List<TaskPart> getTaskPartListForInv(String partUid, String wareHouseUid) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TaskPart getTaskPart(String taskUid, String partUid) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TaskPart> getTaskPartByPartUid(String partUid, Page page) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TaskPart> getTaskPartByTaskUid(String taskUid) throws Exception {
		List<TaskPart> taskParts = new ArrayList<TaskPart>();
		
		Task task = taskDao.getById(taskUid);
		if(task.getTaskType().startsWith("2")) { // 如果关联的是工序任务
			OperationTask operationTask = operationTaskDao.getById(taskUid);
			taskParts.addAll(operationTask.getTaskParts()); 
		} else if(task.getTaskType().startsWith("1")) { // 如果关联的是零件任务
			PartTask partTask = partTaskDao.getById(taskUid);
			List<OperationTask> operationTasks = operationTaskDao.getOperationTasksByParentUid(taskUid);
			
			for(OperationTask operationTask : operationTasks){
				taskParts.addAll(operationTask.getTaskParts());
			}
		}
		
		return taskParts;
	}

}
